package com.company.cloud.common.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.alibaba.fastjson.JSON;
import com.company.cloud.common.bean.ImgEntity;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.StrUtil;

public class ImageNameUtils {

	/**
	 * 获取图片名称含参数
	 * @param imgName:原始图片名称
	 * @param imgW:          原始图片宽
	 * @param imgH:          原始图片高
	 * @param imgParamWH:    处理后图片的宽和高
	 * @return (demo.jpg?wh=50-50&pwh=20-20,30-30)
	 */
	public static String getImgName2Param(String imgName, int imgW, int imgH, Map<Integer, Integer> imgParamWH) {
		String imgParam = "";
		if (imgParamWH != null && imgParamWH.keySet().size() > 0) {
			List<String> imgParamList = new ArrayList<String>();
			imgParamWH.forEach((w, h) -> {
				imgParamList.add(ImageNameUtils.getImgPara(w, h));
			});
			imgParam = StrSplitUtils.list2string(imgParamList);
		}
		
		String urlPara="";
		if (imgW > 0 && imgH > 0) {
			if (StrUtil.isNotEmpty(imgParam)) {
				urlPara=StrUtil.format("wh={}&rwh={}", ImageNameUtils.getImgPara(imgW, imgH), imgParam);
//				return StrUtil.format("{}?wh={}&rwh={}", imgName, ImageNameUtils.getImgPara(imgW, imgH), imgParam);
			} else {
				urlPara=StrUtil.format("wh={}", ImageNameUtils.getImgPara(imgW, imgH));
//				return StrUtil.format("{}?wh={}", imgName, ImageNameUtils.getImgPara(imgW, imgH));
			}
		} else {
			if (StrUtil.isNotEmpty(imgParam)) {
				urlPara=StrUtil.format("rwh={}",imgParam);
//				return StrUtil.format("{}?rwh={}", imgName, imgParam);
			} else {
//				return imgName;
			}
		}
		if(StrUtil.isNotEmpty(urlPara)) {
			return StrUtil.format("{}?p={}", imgName,Base64.encode(urlPara));
		}else {
			return imgName;
		}
	}

	/**
	 * 处理后图片文件名
	 * @param fileName:原文件名
	 * @param w:处理后图片宽
	 * @param h:处理后图片高
	 * */
	public static String getSaveImageName(String fileName, int w, int h) {
		String targetName;
		String resizeName = ImageNameUtils.getImgPara("-", w, h);
		int idx = fileName.lastIndexOf(".");
		if (idx == -1) {
			targetName = StrUtil.format("{}{}", fileName, resizeName);
		} else if (idx == (fileName.length() - 1)) {
			targetName = StrUtil.format("{}{}.", fileName.substring(0, idx), resizeName);
		} else {
			String str = fileName.substring(idx);
			if (StrUtil.isEmpty(str)) {
				targetName = StrUtil.format("{}{}", fileName, resizeName);
				;
			} else {
				targetName = fileName.replace(str, resizeName + str);
			}
		}
		return targetName;

	}
	
	
	

	/**
	 * 获取所有图片信息
	 * */
	public static List<ImgEntity> getImageInfoList(String url) {
		List<ImgEntity> data=new ArrayList<ImgEntity>();  
		
		int idx = url.lastIndexOf("?");
		String fileName;
		if(idx>=0) {
			 fileName=url.substring(0, idx);
		}else {
			fileName=url;
		}
		
		if(StrUtil.isEmpty(fileName)) {
			return data;
		}
		
		Map<String, String> paraMap=getParamByUrl(url);
		//直接取属性值
//		String wh= paraMap.get("wh");
//		String rwh= paraMap.get("rwh");
		
		//base取属性值
		String p=paraMap.get("p");
		if(StrUtil.isEmpty(p)) {
			data.add(new ImgEntity(fileName));
			return data;
		}
		Map<String, String> paraMap2=getParamByUrlParam2Base64(p);
		String wh= paraMap2.get("wh");
		String rwh= paraMap2.get("rwh");

		
		if(StrUtil.isNotEmpty(wh)) {
			ImgEntity imtItem= getImageItem(fileName, wh, false);
			if(imtItem!=null) {
				data.add(imtItem);
			}
		}
		
		if(StrUtil.isNotEmpty(rwh)) {
			List<String> whList= StrSplitUtils.parse2list(rwh, String.class);
			whList.forEach(item->{
				if(StrUtil.isNotEmpty(item)) {
					ImgEntity imgItem=getImageItem(fileName, item, true);
					if(imgItem!=null) {
						data.add(imgItem);
					}
				}
			});
		}
		
		if(data.size()<=0) {
			data.add(new ImgEntity(fileName));
		}
		return data;
	}
	
	
	
	
	
	/**
	 * 根据高获取图片信息
	 * */
	public static ImgEntity getImageInfoByWidth(String url,int w) {
		List<ImgEntity> data=getImageInfoList(url);
		if(CollectionUtil.isNotEmpty(data)) {
			for(ImgEntity item:data) {
				if(item.getW()==w) {
					return item;
				}
			}
		}
		return new ImgEntity(url);
	}
	
	
	private static ImgEntity getImageItem(String fileName, String whs,boolean isProcessName) {
		if(StrUtil.isEmpty(fileName)) {
			return null;
		}
		try {
			ImgEntity data=getImageItemByWH(whs);
			if(isProcessName) {
				String url= getSaveImageName(fileName, data.getW(), data.getH());
				data.setUrl(url);
			}else {
				data.setUrl(fileName);
			}
			return data;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	
	
	/**
	 * URL参数base64解码
	 * */
	public static Map<String, String> getParamByUrlParam2Base64(String urlParamBase64) {
		Map<String, String> data=new HashMap<String, String>();
		String p2= Base64.decodeStr(urlParamBase64);
		if(StrUtil.isEmpty(p2)) {
			return data;
		}
		String[] strs=p2.split("&");
		if(ArrayUtil.isEmpty(strs)) {
			return data;
		}
		for(String str:strs) {
			String[] itemStrs=str.split("=");
			if(itemStrs!=null && itemStrs.length==2) {
				if(StrUtil.isNotEmpty(itemStrs[0]) && StrUtil.isNotEmpty(itemStrs[1])) {
					data.put(itemStrs[0], itemStrs[1]);
				}
			}
		}
		return data;
	} 
	
	/**
	 * 获取指定url中的某个参数
	 * @param url: URL
	 * @param name: 参数名称
	 * @return 参数值
	 */
	public static String getParamByUrl(String url, String name) {
		Map<String, String> data= getParamByUrl(url);
		return data.get(name);
	}
	
	/**
	 * 获取指定url中的某个参数
	 * @param url: URL
	 * @param name: 参数名称
	 * @return 参数值
	 */
	public static Map<String, String> getParamByUrl(String url) {
		String regEx="(\\?|&+)(.+?)=([^&]*)";
		 Pattern p = Pattern.compile(regEx);  
		 Matcher m = p.matcher(url);
		 Map<String, String> paramMap = new LinkedHashMap<String, String>();
		 while(m.find()) {
			 String paramName = m.group(2);//获取参数名
			 String paramVal=m.group(3);//获取参数值
			 paramMap.put(paramName, paramVal);
		 }
		 return paramMap;
	}
	
	

	/**
	 * 在指定url后追加参数
	 * @param url: URL
	 * @param name: 参数名称
	 * @param val: 参数值
	 * @return 含参数的URL
	 */
	public static String appendUrl(String url, String name,String val) {
		Map<String, Object> data=new HashMap<String, Object>();
		data.put(name, val);
		return appendUrl(url, data);
	}
	
	/**
	 * 在指定url后追加参数
	 * @param url: URL
	 * @param data: 参数集合
	 * @return  含参数的URL
	 */
	public static String appendUrl(String url, Map<String, Object> data) {
	    String newUrl = url;
	    StringBuffer param = new StringBuffer();
	    for (String key : data.keySet()) {
	        param.append(key + "=" + data.get(key).toString() + "&");
	    }
	    String paramStr = param.toString();
	    paramStr = paramStr.substring(0, paramStr.length() - 1);
	    if (newUrl.indexOf("?") >= 0) {
	        newUrl += "&" + paramStr;
	    } else {
	        newUrl += "?" + paramStr;
	    }
	    return newUrl;
	}
	
	
	private static String getImgPara(int w, int h) {
		return getImgPara(null, w, h);
	}

	private static ImgEntity getImageItemByWH(String whs) {
		ImgEntity data=new ImgEntity();
		String[] wh= whs.split("-");
		if(wh.length==2) {
			data.setW(Integer.parseInt(wh[0]));
			data.setH(Integer.parseInt(wh[1]));
		}
		return data;
	}
	
	private static String getImgPara(String prefix, int w, int h) {
		if (StrUtil.isEmpty(prefix)) {
			return StrUtil.format("{}-{}", w, h);
		} else {
			return StrUtil.format("{}{}-{}", prefix, w, h);
		}
	}

}
